import { IPSDECalendar, IPSControlNavigatable, IPSDETree, IPSAppDataEntity, IPSDEChart, IPSAppView, IPSAppDEView, IPSSysMap } from '@ibiz/dynamic-model-api';
import { ModelTool, Util, ViewTool } from '../../../util';
import {
  AppExpBarCtrlEvents,
  IAppExpBarCtrlController,
  IParam,
  IUIDataParam,
  IViewStateParam,
} from '../../../interface';
import { AppCtrlControllerBase } from './app-ctrl-controller-base';

/**
 * @description 移动端导航栏部件控制器基类
 * @export
 * @class AppExpBarCtrlController
 * @extends {AppCtrlControllerBase}
 * @implements {IAppExpBarCtrlController}
 */
export class AppExpBarCtrlController extends AppCtrlControllerBase implements IAppExpBarCtrlController {
  /**
   * @description 多数据部件
   * @protected
   * @type {(IPSDECalendar | IPSControlNavigatable | IPSDETree)}
   * @memberof AppExpBarCtrlController
   */
  public xDataControl!: IPSDECalendar | IPSControlNavigatable | IPSDETree | IPSDEChart | IPSSysMap;

  /**
   * @description 多数据部件名称
   * @type {string}
   * @memberof AppExpBarCtrlController
   */
  public xDataControlName: string = '';

  /**
   * @description 导航视图名称
   * @type {*}
   * @memberof AppExpBarCtrlController
   */
  public navView!: any;

  /**
   * @description 导航视图组件
   * @type {*}
   * @memberof AppExpBarCtrlController
   */
  public navViewComponent: any;

  /**
   * @description 导航参数
   * @type {IParam}
   * @memberof AppExpBarCtrlController
   */
  public navParam: IParam = {};

  /**
   * @description 导航上下文
   * @type {IParam}
   * @memberof AppExpBarCtrlController
   */
  public navigateContext: IParam = {};

  /**
   * @description 导航视图参数
   * @type {IParam}
   * @memberof AppExpBarCtrlController
   */
  public navigateParams: IParam = {};

  /**
   * @description 导航过滤项
   * @type {string}
   * @memberof AppExpBarCtrlController
   */
  public navFilter: string = '';

  /**
   * @description 导航关系
   * @type {string}
   * @memberof AppExpBarCtrlController
   */
  public navPSDer: string = '';

  /**
   * @description 选中数据
   * @type {IParam}
   * @memberof AppExpBarCtrlController
   */
  public selection: IParam = {};

  /**
   * @description 工具栏模型数据
   * @type {IParam}
   * @memberof AppExpBarCtrlController
   */
  public toolbarModels: IParam = {};

  /**
   * @description 快速分组数据对象
   * @type {*}
   * @memberof AppExpBarCtrlController
   */
  public quickGroupData: any;

  /**
   * @description 快速分组是否有抛值
   * @type {boolean}
   * @memberof AppExpBarCtrlController
   */
  public isEmitQuickGroupValue: boolean = false;

  /**
   * @description 快速分组模型
   * @type {Array<any>}
   * @memberof AppExpBarCtrlController
   */
  public quickGroupModel: Array<any> = [];

  /**
   * @description 部件模型加载
   * @memberof AppExpBarCtrlController
   */
  public async ctrlModelLoad() {
    await super.ctrlModelLoad();
    this.xDataControlName = this.controlInstance.xDataControlName;
    this.xDataControl = ModelTool.findPSControlByName(this.xDataControlName, this.controlInstance.getPSControls());
    if (this.xDataControl) {
      await this.handleXDataOptions();
    }
  }

  /**
   * @description 处理多数据部件配置
   * @protected
   * @memberof AppExpBarCtrlController
   */
  protected async handleXDataOptions() {
    //  导航上下文
    const navContext = (this.xDataControl as any).getPSNavigateContexts?.();
    if (navContext) {
      this.navigateContext = Util.formatNavParam(navContext);
    }
    // 导航参数
    const navParams = (this.xDataControl as any).getPSNavigateParams?.();
    if (navParams) {
      this.navigateParams = Util.formatNavParam(navParams);
    }
  }

  /**
   * @description 部件初始化
   * @param {*} args 额外参数
   * @memberof AppExpBarCtrlController
   */
  public ctrlInit(args?: any) {
    super.ctrlInit(args);
    if (this.viewState) {
      this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }: IViewStateParam) => {
        if (!Object.is(tag, this.name)) {
          return;
        }
        if (this.xDataControl) {
          this.viewState.next({ tag: this.xDataControlName, action: action, data: data });
        }
      });
    }
  }

  /**
   * @description 选中数据变化
   * @protected
   * @param {IUIDataParam} uiDataParam UI数据
   * @return {*}  {void}
   * @memberof AppExpBarCtrlController
   */
  protected onSelectionChange(uiDataParam: IUIDataParam): void {
    let tempContext: any = {};
    let tempViewParam: any = {};
    const args = uiDataParam?.data || [];
    if (args.length === 0) {
      this.calcToolbarItemState(true);
      return;
    }
    const arg: any = args[0];
    if (this.context) {
      Object.assign(tempContext, Util.deepCopy(this.context));
    }
    if (this.xDataControl) {
      const appDataEntity: IPSAppDataEntity | null = this.xDataControl?.getPSAppDataEntity();
      if (appDataEntity) {
        Object.assign(tempContext, {
          [`${appDataEntity.codeName?.toLowerCase()}`]: arg[appDataEntity.codeName?.toLowerCase()],
        });
        Object.assign(tempContext, {
          srfparentdename: appDataEntity.codeName,
          srfparentdemapname: (appDataEntity as any)?.getPSDEName(),
          srfparentkey: arg[appDataEntity.codeName?.toLowerCase()],
        });
        if (this.navFilter && !Object.is(this.navFilter, '')) {
          Object.assign(tempViewParam, { [this.navFilter]: arg[appDataEntity.codeName?.toLowerCase()] });
        }
        if (this.navPSDer && !Object.is(this.navPSDer, '')) {
          Object.assign(tempViewParam, { [this.navPSDer]: arg[appDataEntity.codeName?.toLowerCase()] });
        }
      }
      if (this.navigateContext && Object.keys(this.navigateContext).length > 0) {
        let _context: any = Util.computedNavData(arg, tempContext, tempViewParam, this.navigateContext);
        Object.assign(tempContext, _context);
      }
      if (this.navigateParams && Object.keys(this.navigateParams).length > 0) {
        let _params: any = Util.computedNavData(arg, tempContext, tempViewParam, this.navigateParams);
        Object.assign(tempViewParam, _params);
      }
      this.selection = {};
      Object.assign(tempContext, { viewpath: this.navView });
      Object.assign(this.selection, {
        viewCompoent: this.navViewComponent,
        navContext: tempContext,
        navParam: tempViewParam,
      });
      this.calcToolbarItemState(false);
      this.ctrlEvent(AppExpBarCtrlEvents.SELECT_CHANGE, args);
    }
  }

  /**
   * @description 计算工具栏权限
   * @protected
   * @param {boolean} state
   * @return {*} 
   * @memberof AppExpBarCtrlController
   */
  protected calcToolbarItemState(state: boolean) {
    const models: any = this.toolbarModels;
    if (models && models.length > 0) {
      for (const key in models) {
        if (!models.hasOwnProperty(key)) {
          return;
        }
        const _item = models[key];
        if (
          _item.uiaction &&
          (Object.is(_item.uiaction.actionTarget, 'SINGLEKEY') || Object.is(_item.uiaction.actionTarget, 'MULTIKEY'))
        ) {
          _item.disabled = state;
        }
        _item.visabled = true;
        if (_item.noprivdisplaymode && _item.noprivdisplaymode === 6) {
          _item.visabled = false;
        }
      }
      ViewTool.calcActionItemAuthState({}, this.toolbarModels, this.appUIService);
    }
  }

  /**
   * 打开视图导航视图
   *
   * @param {IPSDEChartSeries} seriesItem
   * @param {*} tempContext
   * @param {*} args
   * @memberof MobChartExpBarController
   */
  async openExplorerView(explorerView: IPSAppView, args: any, tempContext: any, tempViewParam: any) {
    let deResParameters: any[] = [];
    let parameters: any[] = [];
    if (!explorerView?.isFill) {
      await explorerView?.fill(true);
    }
    const entity: IPSAppDataEntity | null = explorerView?.getPSAppDataEntity();
    if (!entity?.isFill) {
      await entity?.fill(true)
    }
    if (entity) {
      deResParameters = Util.formatAppDERSPath(tempContext, (explorerView as IPSAppDEView)?.getPSAppDERSPaths());
      parameters = [
        {
          pathName: Util.srfpluralize(entity.codeName).toLowerCase(),
          parameterName: entity.codeName.toLowerCase(),
        },
        {
          pathName: 'views',
          parameterName: ((explorerView as IPSAppDEView).getPSDEViewCodeName() as string).toLowerCase(),
        },
      ];
    } else {
      parameters = [{ pathName: 'views', parameterName: explorerView?.codeName.toLowerCase() }];
    }
    const routePath = ViewTool.buildUpRoutePath(tempContext, deResParameters, parameters, args, tempViewParam);
    App.getOpenViewService().openView(routePath);
  }
}
